#!/bin/bash
set -e
# for GPT partition RAID arrays, adds a "stale" secondary disk into the array
if [[ -n `mdadm --detail /dev/md0 /dev/md2 | grep /dev/sdb` ]]; then
        echo "ERROR: \"Secondary\" disk /dev/sdb is already active !!"
        exit 1
elif [[ -n `mdadm --detail /dev/md1 | grep /dev/sdb3` ]]; then
	# Sometimes swap partitions don't detect staleness
        echo "NOTE: \"Secondary\" disk swap partition /dev/sdb2 was active"
	mdadm /dev/md1 -f /dev/sdb3
	mdadm /dev/md1 -r /dev/sdb3
fi
echo "Adding \"Secondary\" disk /dev/sdb to RAID array /dev/md0 ... "
mdadm /dev/md0 -a /dev/sdb2
while [[ -n `grep recovery /proc/mdstat` ]]; do 
	recovery=`grep recovery /proc/mdstat | cut -c32-`
	echo -e -n '\r'$recovery
	sleep 1;
done
echo -e "\ndone."
echo "Installing GRUB bootloader on \"Secondary\" disk /dev/sdb ... "
grub-install --recheck /dev/sdb
echo "done."
echo "Adding \"Secondary\" disk /dev/sdb to RAID array /dev/md1 ... "
mdadm /dev/md1 -a /dev/sdb3
while [[ -n `grep recovery /proc/mdstat` ]]; do 
	recovery=`grep recovery /proc/mdstat | cut -c32-`
	echo -e -n '\r'$recovery
	sleep 1;
done
echo -e "\ndone."
echo "Adding \"Secondary\" disk /dev/sdb to RAID array /dev/md2 ... "
echo "(This may safely be interrupted with 'Control-C' if you don't want to wait)"
mdadm /dev/md2 -a /dev/sdb4
while [[ -n `grep recovery /proc/mdstat` ]]; do 
	recovery=`grep recovery /proc/mdstat | cut -c32-`
	echo -e -n '\r'$recovery
	sleep 1;
done
echo -e "\ndone."
